package com.situ.crm.controller;

import com.situ.crm.util.JSONResult;
import com.situ.crm.util.VerifyCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Controller
@Slf4j
public class LoginController {

    @RequestMapping("/getLoginPage")
    public String getLoginPage() {
        return "login";
    }

    @RequestMapping("/login")
    @ResponseBody
    public JSONResult login(String name, String password, String code,HttpSession session) {
        //比较验证码
        String codes = (String) session.getAttribute("code");
        if (StringUtils.isEmpty(code) || !codes.equalsIgnoreCase(code)){
            return JSONResult.error("验证码错误");
        }
        // if (name == null || "".equals(name)) {}
        // org.apache.commons.lang3
        if (StringUtils.isEmpty(name) || StringUtils.isEmpty(password)) {
            return JSONResult.error("用户名和密码不能为空!");
        }
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(name, password);
        try {
            //进行验证，这里可以捕获异常，然后返回对应信息
            subject.login(token);
        } catch (UnknownAccountException e) {
            log.error("用户名不存在！", e);
            return JSONResult.error("用户名不存在！");
        } catch (AuthenticationException e) {
            log.error("账号或密码错误！", e);
            return JSONResult.error("账号或密码错误！");
        } catch (AuthorizationException e) {
            log.error("没有权限！", e);
            return JSONResult.error("没有权限！");
        }

        return JSONResult.ok("登录成功");
    }

    @RequestMapping("/logout")
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        if (subject != null) {
            subject.logout();
        }
        return "login";
    }

    @RequestMapping("/getImage")
    public void getImage(HttpSession session, HttpServletResponse response) throws IOException {
        //生成验证码
        String code = VerifyCodeUtils.generateVerifyCode(4);
        //验证码放入session
        session.setAttribute("code",code);
        //验证码存入图片
        ServletOutputStream os = response.getOutputStream();
        response.setContentType("image/png");
        VerifyCodeUtils.outputImage(220,60,os,code);
    }
}
